package edu.neumont.App;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.URL;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import edu.neumont.entities.Base64;
import edu.neumont.entities.Entities;
import edu.neumont.entities.Network;
import edu.neumont.entities.User;
import edu.utility.xuggle.MyPicture;
import android.R.bool;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginActivity extends Activity {
	EditText emailField, passwordField;
	TextView loginError;
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.login);        
        
        
		Entities.network = new Network();
		
        loginError = (TextView)findViewById(R.id.loginError);        
        Button b = (Button)findViewById(R.id.loginButton);
        
        emailField = (EditText)findViewById(R.id.userName);
        passwordField = (EditText)findViewById(R.id.password);
        b.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				new LogInTask().execute();		
			}
		}); 
    }
	private void setUpNetwork(String ip, int port){
		Entities.network.setUp(ip, port);
	}
	
	public String encript(String password){
		String encriptedPass = "";
		try{
		MessageDigest md = MessageDigest.getInstance("SHA");
		md.update(password.getBytes("UTF-8"));
		byte raw[] = md.digest();
		String hash = Base64.encodeBytes(raw);
		 encriptedPass = hash;
		}catch(Exception ex){}
		
		System.out.println(encriptedPass);
		return encriptedPass;
		
	}

	class LogInTask extends AsyncTask<Void, HttpResponse, HttpResponse> {
	    protected HttpResponse doInBackground(Void...arg) {
	    	
	    	HttpResponse response =null;
			User user = new User(emailField.getText().toString(), encript(passwordField.getText().toString()));
	        try {
			    HttpClient httpclient = new DefaultHttpClient();
			    HttpPost httppost = new HttpPost("http://steveg.dyndns-web.com:8080/Capstone/ValidateLogin.do");

			    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
			    nameValuePair.add(new BasicNameValuePair("user", new Gson().toJson(user)));
			    httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			    response = httpclient.execute(httppost);
	        } catch (Exception e) { }
		    return response;
	    }
	    protected void onPostExecute(HttpResponse o) {
	    	try{
		    	 User user = new Gson().fromJson(EntityUtils.toString(o.getEntity()).trim(), User.class);	
		    	 if(user.getIPAddress() == null || user.getPort()== 0)
		    		 loginError.setText("Invalid username or password");
		    	 else{
		    		 loginError.setText("");
		    		 setUpNetwork(user.getIPAddress(), user.getPort());
		    		 boolean useLocalhost = ((CheckBox)findViewById(R.id.useLocalhost)).isChecked();
		    		 if(Entities.network.connect(useLocalhost))
		    			 startActivity(new Intent(LoginActivity.this, MenuActivity.class));
		    		 else
		    			 loginError.setText("Cannot connect to server");
		    	 }
	    	}catch(Exception ex){}
	    }
	}
	
}